/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package searcherPackage.Index;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 *
 * @author i_khri
 */
public class Index {

    public Index(){
        entries = new HashMap<Term, PostingsList>();
    }



    public void saveTo(String tmpIndexPath){
        File tmpIndexPathFile = new File(tmpIndexPath);
        File parentFile = tmpIndexPathFile.getParentFile();


        if(!parentFile.exists()){
            parentFile.mkdirs();
        }

        try {
            FileOutputStream fos = new FileOutputStream(tmpIndexPath);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");

            Map<Term, PostingsList> entriesSorted = sortEntries();
            StringBuffer entriesString = new StringBuffer();

            for(Term t : entriesSorted.keySet()){
                entriesString.append(t+entriesSorted.get(t).toString()+"\n");
            }

            osw.write(entriesString.toString());
            osw.close();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }

    }



    private Map<Term, PostingsList> sortEntries() {
        Map<Term, PostingsList> entriesSorted = new TreeMap<Term, PostingsList>();
        entriesSorted.putAll(entries);
        return entriesSorted;
    }



    public void addRecord(Term term, int docId){
        if(entries.containsKey(term)){
            PostingsList pl = entries.get(term);
            pl.addDocId(docId);
        }else{
            PostingsList pl = new PostingsList();
            pl.addDocId(docId);
            entries.put(term, pl);
        }
    }



    public void addPostingsListForTerm(Term term, PostingsList postList){
        entries.put(term, postList);
    }



    public Term addTermPostingsListFromIndexString(String theString){
        Term term = Term.fromIndexString(theString);
        entries.put(term, PostingsList.fromIndexString(theString));
        return term;
    }



    public PostingsList getPostingsList(Term term){
        return entries.get(term);
    }



    public Set<Term> keySet(){
        return entries.keySet();
    }



    public boolean isEmpty(){
        return entries.isEmpty();
    }


    public boolean containsTerm(Term term){
        return entries.containsKey(term);
    }



    public void clear(){
        entries.clear();
    }

    

    private Map<Term, PostingsList> entries;

}

